package com.clg.protobuf.util;

import com.clg.protobuf.entity.User;
import com.clg.protobuf.proto.UserRequestDTO;
import com.google.gson.Gson;
import com.googlecode.protobuf.format.JsonFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import sun.applet.Main;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by chenlong on 2017/5/27.
 */
@Component
public class TestUtil {

	/**
	 * 构建 UserDTO
	 * @param idNo
	 * @return
	 */
	public UserRequestDTO.UserDTO getUserDTO(Integer idNo) {
		User user = this.getUser(idNo);
		UserRequestDTO.UserDTO.Builder builder = UserRequestDTO.UserDTO.newBuilder();
		BeanUtils.copyProperties(user, builder);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		builder.setCreateTime(simpleDateFormat.format(user.getCreateTime()));
		builder.setUpdateTime(simpleDateFormat.format(user.getUpdateTime()));
		UserRequestDTO.UserDTO userDTO = builder.build();
		return userDTO;
	}

	/**
	 * 构建 User
	 * @param idNo
	 * @return
	 */
	public User getUser(Integer idNo) {
		User user = new User();
		user.setIdNo(idNo);
		user.setAccount("protocolBuffer");
		user.setPasswd("123456");
		user.setMobile("18890909090");
		user.setEmail("test@sina.com");
		user.setStatus(1);
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		return user;
	}


	public User convert(UserRequestDTO.UserDTO userDto) {
		JsonFormat jsonFormat = new JsonFormat();
		String jsonData = jsonFormat.printToString(userDto);
		Gson gson = new Gson();
		User user = gson.fromJson(jsonData, User.class);
		return user;
	}

	public static void main(String[] args) {
		TestUtil util = new TestUtil();
        UserRequestDTO.UserDTO userDTO = util.getUserDTO(2);
        for(byte b : userDTO.toByteArray()){
            System.out.print(b);
        }
    }
}
